package cn.edu.ptu.jobfairs.core.utils;

import cn.edu.ptu.jobfairs.basic.common.User;
import cn.edu.ptu.jobfairs.basic.common.VisibleException;
import org.springframework.security.core.context.SecurityContextHolder;

import static cn.edu.ptu.jobfairs.basic.common.Errors.*;


/**
 * Created by Lin Chenxiao on 2019-09-13
 **/
public class UserUtils {
    public static int getId(){
        User user = getUser();
        if (user == null || user.getId() == null) throw new VisibleException(NOT_LOGGED);
        return user.getId();
    }

    public static User getUser(){
        Object user = getPrincipal();
        return user instanceof User ? (User) user : null;
    }

    private static Object getPrincipal(){
        try {
            return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        catch (Exception e) {
            return null;
        }
    }
}
